package com.hmy.cornpestdet.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.hmy.cornpestdet.mapper.UserLoginRegisterMapper;
import com.hmy.cornpestdet.pojo.User;
import com.hmy.cornpestdet.utils.CPDConst;
import com.hmy.cornpestdet.utils.JwtUtils;
import com.hmy.cornpestdet.utils.Result;
import com.hmy.cornpestdet.vo.UserLoginVo;
import com.hmy.cornpestdet.vo.UserRegisterVo;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserLoginRegisterService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private UserLoginRegisterMapper userLoginRegisterMapper;

    public Result register(UserRegisterVo userRegisterVo){
        User user = getUserByPhoneNumber(userRegisterVo.getPhoneNumber());
        if(user != null){
            return Result.Error("该手机号码已被注册");
        }
        user = getUserByUsername(userRegisterVo.getUsername());
        if(user != null){
            return Result.Error("该用户名已被注册");
        }
        //用户名和手机号都不重复，进行注册
        int uid = insertUser(userRegisterVo);
        if(uid > 0){
            return Result.Success("注册成功",null);
        }
        else{
            return Result.Error("注册失败");
        }
    }

    public Result login(UserLoginVo userLoginVo){
        String code = redisTemplate.opsForValue().get(CPDConst.CAPTCHA_CODE);
        if(code.compareTo(userLoginVo.getCode().toLowerCase()) != 0){
            return Result.Error("验证码错误");
        }
        User user = getUserByUsernameAndCharacter(userLoginVo.getUsername(),userLoginVo.getCharacter());
        if(user == null || user.getPassword().compareTo(userLoginVo.getPassword()) != 0){
            return Result.Error("用户或密码错误");
        }
        //成功登录则返回登录成功
        //将当前用户uid存到redis缓存(不存储管理员的，只存储用户的)
        if(user.getCharacter() == 1)redisTemplate.opsForValue().set(CPDConst.CURRENT_USER_UID,String.valueOf(user.getUid()));
        //生成jwt令牌，返回前端
        Map<String,Object> claims = new HashMap<>();
        claims.put("username",user.getUsername());
        claims.put("uid",user.getUid());
        String token = JwtUtils.genToken(claims);
        //将令牌返回给前端
        return Result.Success("登录成功",token);
    }

    public User getUserByUid(int uid){
        return userLoginRegisterMapper.getUserByUid(uid);
    }

    public User getUserByUsername(String username){
        return userLoginRegisterMapper.getUserByUsername(username);
    }

    public User getUserByUsernameAndCharacter(String username,int character){
        return userLoginRegisterMapper.getUserByUsernameAndCharacter(username,character);
    }

    public User getUserByPhoneNumber(String phoneNumber){
        return userLoginRegisterMapper.getUserByPhoneNumber(phoneNumber);
    }

    public List<User> getAllUser(){
        return userLoginRegisterMapper.getAllUser();
    }


    public int insertUser(UserRegisterVo userRegisterVo){
        User user = new User();
        user.setUsername(userRegisterVo.getUsername());
        user.setPassword(userRegisterVo.getPassword());
        user.setCharacter(CPDConst.CHARACTER_NORMAL);
        user.setPhoneNumber(userRegisterVo.getPhoneNumber());
        user.setRegisterDate(userRegisterVo.getRegisterDate());
        user.setProvince(userRegisterVo.getProvince());
        userLoginRegisterMapper.insertUser(user);
        return user.getUid();
    }

    //生成验证码
    public void generateCode(HttpServletResponse response) throws IOException {
        // 创建验证码
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100, 40);
        // 获取验证码内容（用于后续验证用户输入）
        String captchaCode = captcha.getCode();
        //验证码保存到redis缓存,字母全部转为小写
        redisTemplate.opsForValue().set(CPDConst.CAPTCHA_CODE, captchaCode.toLowerCase());
        // 设置响应头
        response.setContentType("image/png");
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        // 将验证码图片写入响应输出流
        captcha.write(response.getOutputStream());
        response.getOutputStream().close();
    }


}
